import { Component } from "react"
import axios from "axios"
import {ADD_ONE,ADD_NUM,CHANGE_BANNER_LIST,CHANGE_PRO_LIST} from './store/types'

import { connect } from "react-redux"
//7.页面组件导入store
// import store from "./store/storeIndex"
class Page1 extends Component {
    componentDidMount() {
        axios.get('http://121.89.205.189:3000/api/pro/list').then(res => {
            // console.log(res.data.data);
            // store.dispatch({ type: CHANGE_PRO_LIST, payload: res.data.data })
            this.props.changePro(res.data.data)
        })

        axios.get('http://121.89.205.189:3000/api/banner/list').then(res=>{
            console.log(res.data.data);
            // store.dispatch({ type: CHANGE_BANNER_LIST, payload: res.data.data })
            this.props.changeBanner(res.data.data)
        })

    }
    render() {
        // console.log(store.getState().count);
        // const count = store.getState().count
        // const proList = store.getState().pro.proList
        return <>
            {/* <h1>Page1-------{store.getState().count.count}</h1> */}
            <h1>Page1-------{this.props.count}</h1>

            <button onClick={() => {
                //修改全局数据
                //触发add
                this.props.add()
            }}>点击加1</button>

            <button onClick={() => {
                //修改全局数据
                //触发add
                // store.dispatch({ type: ADD_NUM, payload: 5 })
                this.props.addNum(5)
            }}>点击加指定数</button>

            <ul>
                {this.props.proList && this.props.proList.map((item) => {
                    return <li key={item.proid}>{item.proname}</li>
                })}
            </ul>

            <ul>
                {this.props.bannerList && this.props.bannerList.map((item,index) => {
                    return  <li key={index}><img src={item.img} style={{width:"350px"}} alt="" /></li>
                })}
            </ul>
        </>
    }
}


// 将全局状态中的数据映射到组件的 props 中
const mapStateToProps = (state) => {
    return {
        count: state.count.count,
        proList: state.pro.proList,
        bannerList: state.pro.bannerList
    }
}
// 将全局的修改方法映射到组件的 props 中
const mapDispatchToProps = (dispatch) => {
    return {
        add: () => {
            dispatch({ type: ADD_ONE})
        },
        addNum: (num) => {
            dispatch({ type: ADD_NUM, payload: num })
        },
        changePro: (value) => {
            dispatch({ type: CHANGE_PRO_LIST, payload:value })
        },
        changeBanner: (value) => {
            dispatch({ type: CHANGE_BANNER_LIST, payload:value })
        }
    }
}

// connect 是用来连接数据和视图的
// connect(映射状态到组件的props中，映射修改函数到组件的props中)
// connect 返回值是一个高阶组件 ,将组件page1传入后返回新的组件带有映射的数据和修改方法
export default connect(mapStateToProps,mapDispatchToProps)(Page1)
// function connect(state) {
//     return (Com) => {
//         <Com state={state}></Com>
//     }
// }
// connect()(Page2)